package com.yrmao.mviewpagergridview.adapter;

import android.content.Context;
import android.support.v4.view.PagerAdapter;
import android.view.View;
import android.view.ViewGroup;

import com.yrmao.mviewpagergridview.modles.GridviewContentInfo;
import com.yrmao.mviewpagergridview.widget.ContentGridLayout;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by yemao on 16/11/30.
 */

public class MViewPagerAdapter extends PagerAdapter {
    private List<GridviewContentInfo> list;
    private Context context;
    private int allpage = 1;//总页数默认为1
    private int pagesize = 4;//每页显示个数

    public MViewPagerAdapter(List<GridviewContentInfo> list, int pagesize, Context context) {
        this.list = list;
        this.context = context;
        this.pagesize = pagesize;
        if (list != null)
            //计算总页数
            if (list.size() % pagesize >= 1) {
                allpage = list.size() / pagesize + 1;
            } else {
                allpage = list.size() / pagesize;
            }
    }

    @Override
    public int getCount() {
        return allpage;
    }

    @Override
    public Object instantiateItem(ViewGroup container, int position) {

        List<GridviewContentInfo> data = new ArrayList<>();

        //计算每页传递数据
        for (int i = position * pagesize; i < (position + 1) * pagesize; i++) {
            if (i >= list.size())
                break;
            data.add(list.get(i));
        }
        ContentGridLayout gridLayout = new ContentGridLayout(context, data, pagesize);
        //添加到父布局
        container.addView(gridLayout);

        return gridLayout;
    }

    @Override
    public boolean isViewFromObject(View view, Object object) {
        return view == object;
    }

    /**
     * 必须重写此方法不重写会报错具体原因在不清楚
     *
     * @param container
     * @param position
     * @param object
     */
    @Override
    public void destroyItem(ViewGroup container, int position, Object object) {
//        super.destroyItem(container, position, object);
    }
}
